package es.dk.hl.commands
{
	import com.adobe.cairngorm.commands.ICommand;
	import com.adobe.cairngorm.control.CairngormEvent;
	import com.facebook.commands.batch.BatchRun;
	import com.facebook.commands.data.CreateObject;
	import com.facebook.commands.data.SetAssociation;
	import com.facebook.data.NumberResultData;
	import com.facebook.data.batch.BatchCollection;
	import com.facebook.data.batch.BatchResult;
	import com.facebook.events.FacebookEvent;
	
	import es.dk.hl.model.HomeLinkModelLocator;

	public class FaceBook_CreateAndSetAssociation_Command implements ICommand
	{
		
		public function FaceBook_CreateAndSetAssociation_Command()
		{
		}
		
		public function execute(event:CairngormEvent):void {
			var batch:BatchCollection = new BatchCollection();
			var o:Object = new Object();
			o["composicion"] = HomeLinkModelLocator.getInstance().composicion;
			var properties:String = '{"composicion":"'+ o["composicion"] +'"}';
			batch.addItem(new CreateObject("composiciones",properties));
			var batchRun:BatchRun = HomeLinkModelLocator.getInstance().facebook.post(new BatchRun(batch)) as BatchRun;
			batchRun.addEventListener(FacebookEvent.COMPLETE, onBatchComplete1);
		}
		
		protected function onBatchComplete1(event:FacebookEvent):void {
			if (event.success) {
				var results:Array = (event.data as BatchResult).results;
				var oidRegistro:String = NumberResultData(results[0]).value.toString();
				HomeLinkModelLocator.getInstance().composicion_id = Number(oidRegistro);
				var batch:BatchCollection = new BatchCollection();
				batch.addItem(new SetAssociation("usercompo",HomeLinkModelLocator.getInstance().facebookUser.uid,oidRegistro));
				var batchRun:BatchRun = HomeLinkModelLocator.getInstance().facebook.post(new BatchRun(batch)) as BatchRun;
				batchRun.addEventListener(FacebookEvent.COMPLETE, onBatchComplete2);
			}
		}	

		protected function onBatchComplete2(event:FacebookEvent):void {
			if (event.success) {
			}
		}	


	}
}